package cn.linstudy.base;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5Utils {


    private Md5Utils() {}

    /**
     * 标准的调用的MD5加密
     *
     * @param value md5加密
     * @return 返回加密后的字符串
     */
    public static String encode(String value) {
        return encode(value.getBytes());
    }

    /**
     * 标准的调用的MD5加密
     *
     * @param value md5加密
     * @return 返回加密后的字符串
     */
    public static String encode(byte[] value) {
        String result = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(value);
            result = toHex(md.digest());
        } catch (NoSuchAlgorithmException e2) {
            e2.printStackTrace();
        }
        return result;
    }

    /**
     * 加密
     *
     * @param buffer 加密byte数组
     * @return md5字符串
     */
    private static String toHex(byte[] buffer) {
        StringBuilder sb = new StringBuilder(buffer.length * 2);
        for (byte b : buffer) {
            sb.append(Character.forDigit((b & 0xf0) >> 4, 16));
            sb.append(Character.forDigit(b & 0x0f, 16));
        }
        return sb.toString();
    }


}
